package org.geeks.gsjetcache.api;

import java.util.Map;

import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alicp.jetcache.anno.CacheInvalidate;
import com.alicp.jetcache.anno.CachePenetrationProtect;
import com.alicp.jetcache.anno.CacheRefresh;
import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.Cached;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;

import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("cache")
@Slf4j
public class JetCacheApi {

	@Cached(cacheType = CacheType.REMOTE, name = "cache:simple")
	@GetMapping("simple")
	public Map<String, Object> simple() {
		Map<String, Object> result = Maps.newHashMap();
		result.put("ts", System.currentTimeMillis());

		return result;
	}

	@Cached(cacheType = CacheType.BOTH, name = "cache:", key = "#id", expire = 60 * 60)
	@CacheRefresh(refresh = 60, stopRefreshAfterLastAccess = 5 * 60)
	@CachePenetrationProtect
	@GetMapping("byId")
	public Map<String, Object> byId(Long id) {
		log.info("Execute method logic, id [{}]", id);

		Assert.notNull(id, "Id can not be null");

		Map<String, Object> result = Maps.newHashMap();
		result.put("id", id);
		result.put("ts", System.currentTimeMillis());

		return result;
	}

	@CacheInvalidate(name = "cache:", key = "#id")
	@GetMapping("byIdUpdate")
	public Map<String, Object> byIdUpdate(Long id) {

		return ImmutableMap.of("status", "ok");
	}

}
